<template>
  <Layout>
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
      <div class="bg-white rounded-lg shadow-md overflow-hidden">
        <div class="px-6 py-4 border-b flex justify-between items-center">
          <h1 class="text-2xl font-bold text-gray-900">浏览历史</h1>
          <button
            v-if="histories.length > 0"
            @click="clearHistory"
            class="px-4 py-2 text-sm text-red-600 hover:text-red-800"
          >
            清空历史
          </button>
        </div>

        <!-- 筛选和搜索 -->
        <div class="px-6 py-4 border-b bg-gray-50">
          <div class="flex flex-col sm:flex-row gap-4">
            <div class="flex-1">
              <input
                v-model="searchQuery"
                type="text"
                placeholder="搜索文章标题..."
                class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-blue-500 focus:border-blue-500"
              />
            </div>
            <select
              v-model="timeFilter"
              class="px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-blue-500 focus:border-blue-500"
            >
              <option value="all">全部时间</option>
              <option value="today">今天</option>
              <option value="week">本周</option>
              <option value="month">本月</option>
            </select>
            <select
              v-model="sortBy"
              class="px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-blue-500 focus:border-blue-500"
            >
              <option value="time">按时间排序</option>
              <option value="views">按阅读次数</option>
            </select>
          </div>
        </div>

        <!-- 历史记录列表 -->
        <div class="p-6">
          <div v-if="loading" class="text-center py-8">
            <div class="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
            <p class="mt-2 text-gray-500">加载中...</p>
          </div>

          <div v-else-if="filteredHistories.length === 0" class="text-center py-8">
            <svg class="mx-auto h-12 w-12 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
            </svg>
            <p class="mt-2 text-gray-500">暂无浏览记录</p>
          </div>

          <div v-else class="space-y-4">
            <!-- 按日期分组 -->
            <div v-for="group in groupedHistories" :key="group.date" class="space-y-2">
              <h3 class="text-sm font-semibold text-gray-500 uppercase tracking-wider">
                {{ group.label }}
              </h3>

              <div class="space-y-3">
                <article
                  v-for="history in group.items"
                  :key="history.id"
                  class="bg-gray-50 rounded-lg p-4 hover:bg-gray-100 transition-colors"
                >
                  <div class="flex justify-between items-start">
                    <div class="flex-1">
                      <div class="flex items-center space-x-2 mb-2">
                        <Link
                          :href="`/posts/${history.post.slug}`"
                          class="text-lg font-semibold text-gray-900 hover:text-blue-600"
                        >
                          {{ history.post.title }}
                        </Link>
                        <span v-if="history.view_count > 1" class="px-2 py-1 text-xs bg-blue-100 text-blue-800 rounded-full">
                          {{ history.view_count }}次
                        </span>
                      </div>

                      <div class="flex items-center space-x-4 text-sm text-gray-500">
                        <div class="flex items-center space-x-1">
                          <img
                            :src="history.post.user?.avatar || `https://ui-avatars.com/api/?name=${history.post.user?.name}`"
                            :alt="history.post.user?.name"
                            class="w-5 h-5 rounded-full"
                          />
                          <span>{{ history.post.user?.name }}</span>
                        </div>
                        <span>•</span>
                        <span>{{ history.post.category?.name }}</span>
                        <span>•</span>
                        <span>{{ formatTime(history.last_viewed_at) }}</span>
                        <span v-if="history.read_progress > 0" class="text-green-600">
                          • 已读 {{ history.read_progress }}%
                        </span>
                      </div>

                      <p class="mt-2 text-gray-600 line-clamp-2">
                        {{ history.post.excerpt }}
                      </p>

                      <!-- 阅读进度条 -->
                      <div v-if="history.read_progress > 0" class="mt-3">
                        <div class="w-full bg-gray-200 rounded-full h-1.5">
                          <div
                            class="bg-green-600 h-1.5 rounded-full"
                            :style="`width: ${history.read_progress}%`"
                          ></div>
                        </div>
                      </div>

                      <!-- 标签 -->
                      <div v-if="history.post.tags?.length > 0" class="mt-3 flex flex-wrap gap-2">
                        <span
                          v-for="tag in history.post.tags"
                          :key="tag.id"
                          class="px-2 py-1 text-xs bg-gray-200 text-gray-700 rounded"
                        >
                          {{ tag.name }}
                        </span>
                      </div>
                    </div>

                    <!-- 操作菜单 -->
                    <div class="ml-4 flex-shrink-0">
                      <button
                        @click="removeHistory(history.id)"
                        class="p-2 text-gray-400 hover:text-red-600"
                        title="删除记录"
                      >
                        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                        </svg>
                      </button>
                    </div>
                  </div>
                </article>
              </div>
            </div>
          </div>

          <!-- 分页 -->
          <div v-if="totalPages > 1" class="mt-6 flex justify-center">
            <nav class="flex space-x-2">
              <button
                @click="currentPage--"
                :disabled="currentPage === 1"
                class="px-3 py-2 rounded-md border border-gray-300 text-sm font-medium text-gray-700 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
              >
                上一页
              </button>

              <button
                v-for="page in visiblePages"
                :key="page"
                @click="currentPage = page"
                class="px-3 py-2 rounded-md text-sm font-medium"
                :class="currentPage === page
                  ? 'bg-blue-600 text-white'
                  : 'border border-gray-300 text-gray-700 hover:bg-gray-50'"
              >
                {{ page }}
              </button>

              <button
                @click="currentPage++"
                :disabled="currentPage === totalPages"
                class="px-3 py-2 rounded-md border border-gray-300 text-sm font-medium text-gray-700 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
              >
                下一页
              </button>
            </nav>
          </div>
        </div>
      </div>

      <!-- 统计信息 -->
      <div class="mt-6 bg-white rounded-lg shadow-md p-6">
        <h2 class="text-lg font-semibold mb-4">阅读统计</h2>
        <div class="grid grid-cols-1 sm:grid-cols-3 gap-6">
          <div class="text-center">
            <div class="text-3xl font-bold text-blue-600">{{ stats.total_views }}</div>
            <div class="text-sm text-gray-500 mt-1">总浏览量</div>
          </div>
          <div class="text-center">
            <div class="text-3xl font-bold text-green-600">{{ stats.unique_posts }}</div>
            <div class="text-sm text-gray-500 mt-1">浏览文章数</div>
          </div>
          <div class="text-center">
            <div class="text-3xl font-bold text-purple-600">{{ stats.reading_time }}</div>
            <div class="text-sm text-gray-500 mt-1">阅读时长（分钟）</div>
          </div>
        </div>

        <!-- 最常访问的分类 -->
        <div v-if="stats.top_categories?.length > 0" class="mt-6">
          <h3 class="text-sm font-semibold text-gray-700 mb-3">最常访问的分类</h3>
          <div class="space-y-2">
            <div v-for="category in stats.top_categories" :key="category.id" class="flex items-center">
              <div class="flex-1">
                <div class="flex justify-between items-center mb-1">
                  <span class="text-sm text-gray-700">{{ category.name }}</span>
                  <span class="text-sm text-gray-500">{{ category.count }}篇</span>
                </div>
                <div class="w-full bg-gray-200 rounded-full h-2">
                  <div
                    class="bg-blue-600 h-2 rounded-full"
                    :style="`width: ${(category.count / stats.unique_posts) * 100}%`"
                  ></div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </Layout>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { Link } from '@inertiajs/inertia-vue3'
import Layout from '@/Components/Layout.vue'
import axios from 'axios'

const loading = ref(false)
const histories = ref([])
const searchQuery = ref('')
const timeFilter = ref('all')
const sortBy = ref('time')
const currentPage = ref(1)
const perPage = 20

const stats = ref({
  total_views: 0,
  unique_posts: 0,
  reading_time: 0,
  top_categories: []
})

// 过滤后的历史记录
const filteredHistories = computed(() => {
  let result = [...histories.value]

  // 搜索过滤
  if (searchQuery.value) {
    result = result.filter(h =>
      h.post.title.toLowerCase().includes(searchQuery.value.toLowerCase())
    )
  }

  // 时间过滤
  const now = new Date()
  if (timeFilter.value === 'today') {
    const today = new Date(now.getFullYear(), now.getMonth(), now.getDate())
    result = result.filter(h => new Date(h.last_viewed_at) >= today)
  } else if (timeFilter.value === 'week') {
    const weekAgo = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000)
    result = result.filter(h => new Date(h.last_viewed_at) >= weekAgo)
  } else if (timeFilter.value === 'month') {
    const monthAgo = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000)
    result = result.filter(h => new Date(h.last_viewed_at) >= monthAgo)
  }

  // 排序
  if (sortBy.value === 'views') {
    result.sort((a, b) => b.view_count - a.view_count)
  } else {
    result.sort((a, b) => new Date(b.last_viewed_at) - new Date(a.last_viewed_at))
  }

  return result
})

// 分页后的历史记录
const paginatedHistories = computed(() => {
  const start = (currentPage.value - 1) * perPage
  const end = start + perPage
  return filteredHistories.value.slice(start, end)
})

// 按日期分组
const groupedHistories = computed(() => {
  const groups = {}
  const now = new Date()
  const today = new Date(now.getFullYear(), now.getMonth(), now.getDate())
  const yesterday = new Date(today.getTime() - 24 * 60 * 60 * 1000)

  paginatedHistories.value.forEach(history => {
    const date = new Date(history.last_viewed_at)
    const dateKey = date.toDateString()

    let label = dateKey
    if (date >= today) {
      label = '今天'
    } else if (date >= yesterday) {
      label = '昨天'
    } else {
      label = formatDate(date)
    }

    if (!groups[dateKey]) {
      groups[dateKey] = {
        date: dateKey,
        label,
        items: []
      }
    }
    groups[dateKey].items.push(history)
  })

  return Object.values(groups)
})

// 总页数
const totalPages = computed(() => {
  return Math.ceil(filteredHistories.value.length / perPage)
})

// 可见页码
const visiblePages = computed(() => {
  const pages = []
  const start = Math.max(1, currentPage.value - 2)
  const end = Math.min(totalPages.value, currentPage.value + 2)

  for (let i = start; i <= end; i++) {
    pages.push(i)
  }

  return pages
})

const formatDate = (date) => {
  const d = new Date(date)
  return `${d.getMonth() + 1}月${d.getDate()}日`
}

const formatTime = (date) => {
  const d = new Date(date)
  const now = new Date()
  const diff = now - d

  if (diff < 60000) {
    return '刚刚'
  } else if (diff < 3600000) {
    return `${Math.floor(diff / 60000)}分钟前`
  } else if (diff < 86400000) {
    return `${Math.floor(diff / 3600000)}小时前`
  } else {
    return formatDate(d)
  }
}

const loadHistory = async () => {
  loading.value = true
  try {
    const response = await axios.get('/api/user/history')
    histories.value = response.data.histories
    stats.value = response.data.stats
  } catch (error) {
    console.error('加载历史记录失败:', error)
  } finally {
    loading.value = false
  }
}

const removeHistory = async (id) => {
  if (!confirm('确定删除这条记录吗？')) return

  try {
    await axios.delete(`/api/user/history/${id}`)
    histories.value = histories.value.filter(h => h.id !== id)
  } catch (error) {
    console.error('删除失败:', error)
    alert('删除失败，请重试')
  }
}

const clearHistory = async () => {
  if (!confirm('确定清空所有浏览历史吗？此操作不可恢复。')) return

  try {
    await axios.delete('/api/user/history')
    histories.value = []
    stats.value = {
      total_views: 0,
      unique_posts: 0,
      reading_time: 0,
      top_categories: []
    }
  } catch (error) {
    console.error('清空失败:', error)
    alert('清空失败，请重试')
  }
}

onMounted(() => {
  loadHistory()
})
</script>

<style scoped>
.line-clamp-2 {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}
</style>